package com.saltedfish.tool.ui.user

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import androidx.annotation.RequiresApi
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.popwindow.AlertTitleDialog
import cn.droidlover.xdroidmvp.router.Router
import cn.droidlover.xdroidmvp.util.ActivityManager
import cn.droidlover.xdroidmvp.util.ToastUtils
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.constant.StringConstant
import com.saltedfish.tool.dao.AppDataUtils
import com.saltedfish.tool.dao.DayDBDao
import com.saltedfish.tool.dao.SubFlagModelDao
import com.saltedfish.tool.dialog.LoadingDialogs
import com.saltedfish.tool.dialog.PolicyAgreeDialog
import com.saltedfish.tool.dialog.UILoginDialog
import com.saltedfish.tool.dialog.UIServiceDialog
import com.saltedfish.tool.model.DayTable
import com.saltedfish.tool.model.SmallTable
import com.saltedfish.tool.model.ThirdLoginInfo
import com.saltedfish.tool.model.UserInfo
import com.saltedfish.tool.present.LoginAP
import com.saltedfish.tool.ui.MainActivity
import com.saltedfish.tool.ui.XActivity
import com.saltedfish.tool.util.*
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_login.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class LoginActivity : XActivity<LoginAP>(){


    override fun getLayoutId(): Int {
        setStatusColor(true, 1)
        setStatusBlack()
        return R.layout.activity_login
    }

    private val mHandler = Handler()
    override fun initData(savedInstanceState: Bundle?) {
        showSerice =  SharePreferceUtils.getString("showSerice")
        if(TextUtils.isEmpty(showSerice)){
            showDialogData()
        }else{
            initBottomView()
        }
        cal = Calendar.getInstance()
        gifUtils = GIFUtils()

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ThirdLoginInfo> { loginInfo ->
                    if (loginInfo != null) {
                        //  XLog.e("wx Info","----登录成功后请求后台--->>>"+loginInfo.toString())
                        mHandler.postDelayed(Runnable {
                            p.login(loginInfo)
                        }, 100)

                    }
                })

        //权限
//       checkStoragePermission()


    }


    override fun newP(): LoginAP? {
        return LoginAP()
    }

    private var  gifUtils : GIFUtils? =null

    private var  dialog : UILoginDialog? =null
    private var  serviceDialog : UIServiceDialog? =null


    /**
     * 初始化底部的view
     */
    private fun initBottomView() {
        if (dialog == null) {
            dialog = UILoginDialog(context)
            dialog!!.setSimpleListener(object : SimpleListener<Int>() {
                @RequiresApi(Build.VERSION_CODES.M)
                override fun onClick(type: String) {
                    if (type == "wxLogin") {

                        onClickWeChatLogin()

                    } else if (type == "userService") {

                        initServiceView("userService")

                    } else if (type == "userSecret") {
                        initServiceView("userSecret")
                    }
                }
            })
        }
        dialog!!.setCanceledOnTouchOutside(false)
        dialog!!.setOnKeyBackListener(true)
        dialog!!.show()

    }

    private var confirmDialog : PolicyAgreeDialog?=null

    private fun showDialogData() {
        if (confirmDialog == null) {
            confirmDialog = PolicyAgreeDialog(context)
            confirmDialog!!.setDesc()
            confirmDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
                    if (type == "1") {
                        ToastUtils.showMessage(context, "您需要同意后才可继续使用咸鱼Flag提供的服务")
                        finish()
                    } else if(type == "2") {
                        SharePreferceUtils.setString("showSerice","showSerice")
                        initBottomView()
                    } else  {
                        initServiceView(type)
                    }
                }
            })
        }
        confirmDialog!!.setCanceledOnTouchOutside(false)
        confirmDialog!!.show()
    }


    /**
     *
     */
    private fun initServiceView(type: String) {
        if (serviceDialog == null) {
            serviceDialog = UIServiceDialog(context)
        }
        serviceDialog!!.initService(type)
        serviceDialog!!.show()

    }

    var dayDBDao: DayDBDao? = null
    var subFlagModelDao: SubFlagModelDao? = null

    var cal: Calendar? = null

    var showGif: String? = null
    var showSerice: String? = null


    private fun onClickWeChatLogin() {
        if (StringConstant.wx_api == null) {
            StringConstant.wx_api = WXAPIFactory.createWXAPI(this, StringConstant.APP_ID, true)
        }
        if (!StringConstant.wx_api.isWXAppInstalled) {
            ToastUtils.showMessageBottom(context, "您手机尚未安装微信，请安装后再登录")
            return
        }

        StringConstant.wx_api.registerApp(StringConstant.APP_ID)
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "wechat_sdk_xb_live_state" //官方说明：用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
        StringConstant.wx_api.sendReq(req)
    }
    /**
     * 登录成功
     */
    fun loginSuccess(userInfo: UserInfo) {
        if(dialog !=null){
            dialog!!.dismiss()
        }
        //权限
        checkStoragePermission()

    }


    //检查相关权限
    private fun checkStoragePermission() {
        if (
                 rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)
                && rxPermissions.isGranted(Manifest.permission.WRITE_CALENDAR)
        ) {
            insertDayDB()
        } else {
            rxPermissions.request(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_CALENDAR,
                    Manifest.permission.WRITE_CALENDAR
            ).subscribe { t ->
                if (t) {
                    insertDayDB()
                }else{
                    loadOneTimeGif()
                    gifUtils!!.setGifListener {
                        mHandler.postDelayed(Runnable {
                            Router.newIntent(context)
                                .to(MainActivity::class.java).launch()
                            finish()

                        }, 1000)
                    }
                }
            }.isDisposed
        }

    }

    private fun loadOneTimeGif(){
        showGif =  SharePreferceUtils.getString("showGif")
        if(TextUtils.isEmpty(showGif)){
            mHandler.postDelayed(Runnable {
                gifUtils!!.loadOneTimeGif(context, R.drawable.login_start, ivFirstBGMGif)
            }, 10)
            SharePreferceUtils.setString("showGif","showGif")
        }
    }

    fun insertDayDB() {

        loadOneTimeGif()

        //储存下载文件的目录
        val dir = File(StringConstant.STORAGE_DIR)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val file = File(dir, StringConstant.DbBase)
        if (file.exists()) {
          var flags = FileSizeUtil.deleteFiles(file)
            if(flags){
              //  LoadingDialogs.getInstance(context).show()
                Thread{
                    p.downloadFile(context)
                }.start()
            }
        }else{
           // LoadingDialogs.getInstance(context).show()
            Thread{
                p.downloadFile(context)
            }.start()
        }

//        LoadingDialogs.getInstance(context).dismiss()
//        Router.newIntent(context)
//                .to(MainActivity::class.java).launch()
//        finish()



    }

    /**
     * 下载成功
     */
    fun downloadFileSuccess(flag:Boolean) {
       // LoadingDialogs.getInstance(context).dismiss()
        var database = AppDataUtils.initRooms(context,flag)

        if(flag){
            Thread{
                subFlagModelDao = database.subFlagDao()
                var subFlagModelLists = subFlagModelDao!!.getAllByStatusAndProgress(1.0f, "暂未开始", "进行中")
                for (item in subFlagModelLists) {
                    CalendarReminderUtils.addCalendarEvent(context, item)
                }

            }.start()
        }

        if(!TextUtils.isEmpty(showGif)){
            Router.newIntent(context)
                .to(MainActivity::class.java).launch()
            finish()
        }else{
            gifUtils!!.setGifListener {
                mHandler.postDelayed(Runnable {
                    Router.newIntent(context)
                        .to(MainActivity::class.java).launch()
                    finish()

                }, 1000)
            }
        }

    }




    private var exitTime: Long = 0

    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2500) {
            ToastUtils.showMessageBottom(this, "再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            //安全退出
            //stopService(intentIm)
            ActivityManager.getInstance().exitApp()
        }
    }



}
